/*
 * Created on Mar 8, 2004
 */
package com.scalar.chiptrack.operations.packingslip.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLineItems;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;

/**
 * @author Ravikanth
**/
public class ViewPackingSlipAction
{
	private static String ERROR_MESSAGE_CONTACT_SYS_ADMN = "Please.. Contact <a href='javascript:showErrorReportPage()'>System Administrator</a>";

	
	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception 
	{
		HttpSession session = request.getSession();
		HashMap errors		= new HashMap();
		String returnVal 	= "failure";
		String action 		= request.getParameter( "action" );
		boolean dropShip	= false;
		int customerShippingId  = -1 ;

        if ( request.getParameter("mode") == null )
        {
            session.removeAttribute	( SessionKeys.FINAL_INVENTORY_MAP );
            session.removeAttribute	( "orgFinalInventoryDataList" );
        }
		session.removeAttribute	( "repetedPartNumber" );
		request.setAttribute 	( "showNoModifyMessage", "TRUE" );

        if ( request.getParameter("mode") != null && request.getParameter("mode").equalsIgnoreCase("back") )
        {
            boolean success = false;
            try
			{
                int shippingAddressId = -1;
                int customerId = -1;
                ArrayList shippingAddresses =  null;

                PackingSlipForm packingSlipForm = ( PackingSlipForm ) session.getAttribute ( "packingSlipForm" );
                String vendorLocationName = VendorDAO.getLocationByAddressId( packingSlipForm.getShippingFromLocationId(), Constants.LOCATION_TYPE_FINISHED_GOODS );
                request.setAttribute("vendorLocationName",vendorLocationName);
                // Load all packingslips generated for this sales order
                ArrayList  packingSlipListBySalesOrderId  = NewPackingSlipDAO.loadPackingSlipsBySalesOrderId ( packingSlipForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED );
                // setPackingSlipOrder( packingSlipListBySalesOrderId , request , packingSlipForm.getLabel() );
                request.setAttribute ( "packingSlipListBySalesOrderId",  new ViewPackingSlipAction().setPackingSlipOrder ( packingSlipListBySalesOrderId , packingSlipForm.getLabel() ) );
                // repeting part numbers
                ArrayList repetedPartNumber = new ArrayList();
                repetedPartNumber = NewPackingSlipDAO.getRepetedPartNumbers ( packingSlipForm.getLineitems() );

                if( repetedPartNumber.size() > 0 )
                {
                    session.setAttribute( "repetedPartNumber", repetedPartNumber );
                }

                CustomerShippingLineItems lineItem = null;
                ArrayList lineItems = packingSlipForm.getLineitems();
                ArrayList tempPartNoList = null;
                int[] isDisableSubstitutableList;
                if( lineItems != null && lineItems.isEmpty() == false )
                {
                    isDisableSubstitutableList = new int[lineItems.size()];
                    int invPulledQty = -1;
                    for ( int i = 0; i < lineItems.size() ; i++ )
                    {
                        lineItem = ( CustomerShippingLineItems ) lineItems.get (i);
                        //try{
                            invPulledQty = lineItem.getQtyPulled() ;
                            if( invPulledQty > 0 )
                                isDisableSubstitutableList[i] = 1 ;
                            else
                                isDisableSubstitutableList[i] = 0 ;
                        //}catch(NumberFormatException nfe){ isDisableSubstitutableList[i] = 1; };
                    }
                    request.setAttribute( "isDisableSubstitutableList", isDisableSubstitutableList );
                }

                if ( ( packingSlipForm.getNewShippingAddressId () == -1 ) && ( session.getAttribute ( "newPSShippingAddressId" ) != null ) )
                {
                    try{
                        packingSlipForm.setNewShippingAddressId ( Integer.parseInt ( ( String ) session.getAttribute ( "newPSShippingAddressId" ) ) );
                    }catch(NumberFormatException nfe){ };
                }
                if( packingSlipForm.getNewShippingAddressId() <= 0 )
                {
                    if( packingSlipForm.getNewHiddenShippingAddressId() <= 0 )
                        shippingAddressId = packingSlipForm.getShippingToAddressId();
                    else
                        shippingAddressId = packingSlipForm.getNewHiddenShippingAddressId();
                }
                else
                {
                    shippingAddressId = packingSlipForm.getNewShippingAddressId();
                }

                customerId = NewSalesOrderDAO.getCustomerID( null, packingSlipForm.getSalesOrderId() + "" );
                if ( packingSlipForm.getOdmId() > 0 )
                {
                    shippingAddresses = CustomerDAO.getAllAddressesOfType( packingSlipForm.getOdmId(), Constants.ADDRESS_TYPE_SHIPPING) ;
                    shippingAddresses.add ( 0, CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( packingSlipForm.getOdmId() ) ) );
                    shippingAddresses.add ( CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( customerId ) ) );
                }
                else
                {
                    shippingAddresses = CustomerDAO.getAllAddressesOfType( customerId, Constants.ADDRESS_TYPE_SHIPPING) ;
                    shippingAddresses.add ( 0, CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( customerId ) ) );
                }
                session.setAttribute ( "psShippingAddresses", loadAddresses( shippingAddresses ) );

                packingSlipForm.setNewShippingAddress( NewPackingSlipDAO.loadShippingAddressDetails( null, shippingAddressId  ) );

                if( packingSlipForm.getNewShippingAddress() != null && packingSlipForm.getNewShippingAddress().getContactPerson() != null && packingSlipForm.getNewShippingAddress().getContactPerson().trim().length() > 0 )
                {
                    packingSlipForm.setContactPerson( packingSlipForm.getNewShippingAddress().getContactPerson() );
                }
                else
                {
                    packingSlipForm.setContactPerson( "" );
                }
                if( packingSlipForm.getNewShippingAddress() != null)
                {
                    packingSlipForm.setShippingAddressObject( packingSlipForm.getNewShippingAddress() );
                    packingSlipForm.setShippingAddress( packingSlipForm.getNewShippingAddress() != null ? packingSlipForm.getNewShippingAddress().getAddressAsString() : ""  );
                }
                packingSlipForm.setNewHiddenShippingAddressId( shippingAddressId );

                int billingAddressId = packingSlipForm.getBillingAddressId();
                packingSlipForm.setBillingAddressObject( CustomerDAO.getAddress( billingAddressId  )  ); //contact person details included in Address itself, no need to fetch seperately.
                if( packingSlipForm.getNewBillingAddressId() > 0 ) {
                    billingAddressId = packingSlipForm.getNewBillingAddressId();
                    packingSlipForm.setBillingAddressObject( CustomerDAO.getAddressWithContactPersonDetails( billingAddressId  )  );
                }

                packingSlipForm.setBillingAddress( packingSlipForm.getBillingAddressObject() != null ? packingSlipForm.getBillingAddressObject().getAddressAsString() : ""  );

                ArrayList billingAddresses = CustomerDAO.getAllAddressesOfType( customerId, Constants.ADDRESS_TYPE_BILLING) ;
                billingAddresses.add ( 0, CustomerDAO.getAddress ( SalesOrderDAO.getDefaultBillingAddressId( customerId ) ) );
                request.setAttribute ( "psBillingAddresses", loadAddresses( billingAddresses ) );

                //System.out.println("----------------VIEW-PS-ACTION--BACKOPT--shippingAddressId = " + shippingAddressId);
                session.setAttribute ( "packingSlipForm", packingSlipForm );
                success = true;
            }
            catch ( Exception se )
			{
				success = false;
			}
            if( success )
            {
                return ( mapping.findForward ( "success" ) );
            }
            else
            {
                errors.put ("Internal Server Error", "Could not load Packing Slip");
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                return ( mapping.findForward ( "packingSlipMenu" ) );
            }
        }

		try
		{ 
			customerShippingId = Integer.parseInt ( ( String ) request.getParameter ( "customerShippingId" ) ); 
		} 
		catch (NumberFormatException nfe) {}
		
		if ( ( customerShippingId != -1 ) )
		{
			boolean success = false;
			PackingSlipForm packingSlipForm = null;
			
			try
			{
				packingSlipForm = NewPackingSlipDAO.loadPackingSlipById ( customerShippingId );
				packingSlipForm.setAction( action );

                //Commented by Krishna Prasad on 02 June 2004
				//String vendorLocationName = VendorDAO.getLocationByAddressId( packingSlipForm.getShippingFromAddressId(), Constants.LOCATION_TYPE_FINISHED_GOODS );
                //Added by Krishna Prasad on 02 June 2004
                String vendorLocationName = VendorDAO.getLocationByAddressId( packingSlipForm.getShippingFromLocationId(), Constants.LOCATION_TYPE_FINISHED_GOODS );
                request.setAttribute("vendorLocationName",vendorLocationName);
                request.setAttribute( "weightMeasurementList", NewPackingSlipDAO.loadWeightMeasurements() );
				request.setAttribute( "uomPgkDimensionList", NewPackingSlipDAO.loadUomPkgDimensionList() );
                success = true;
			}
			catch ( ScalarException se )
			{
				errors.put ("Internal Server Error", "Could not load Packing Slip");
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
				session.setAttribute( SessionKeys.ERROR_REPORT, se );
				request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
			}

			if ( success == true )
			{
				if ( "labelView".equalsIgnoreCase ( action) )
				{
                     //Added by Krishna Prasad on 29 May 2004
                     packingSlipForm.setFinalInventoryDataMap( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) );
                     request.setAttribute( "loadInnerOuterBoxById" , NewPackingSlipDAO.loadInnerOuterBoxById( packingSlipForm ) );
					 returnVal = "viewLabels";
				}
				if( "printView".equalsIgnoreCase ( action ) )
				{
					packingSlipForm.setFinalInventoryDataMap( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) );
					returnVal = "packingSlipView";
				}
				else
				{
					// Load all packingslips generated for this sales order
					ArrayList  packingSlipListBySalesOrderId  = NewPackingSlipDAO.loadPackingSlipsBySalesOrderId ( packingSlipForm.getSalesOrderId(), Constants.CUSTOMER_SHIPPING_STATUS_ISSED );
					// setPackingSlipOrder( packingSlipListBySalesOrderId , request , packingSlipForm.getLabel() );
			        request.setAttribute ( "packingSlipListBySalesOrderId",  setPackingSlipOrder ( packingSlipListBySalesOrderId , packingSlipForm.getLabel() ) );
                    CustomerShippingLineItems lineItem = null;
                    ArrayList lineItems = packingSlipForm.getLineitems();
                    int[] isDisableSubstitutableList;
                    if( lineItems != null && lineItems.isEmpty() == false )
                    {
                        isDisableSubstitutableList = new int[lineItems.size()];
                        for ( int i = 0; i < lineItems.size() ; i++ )
                        {
                            lineItem = ( CustomerShippingLineItems ) lineItems.get (i);
                            if( lineItem.getOrginalQtyPulled() > 0 )
                                isDisableSubstitutableList[i] = 1 ;
                            else
                                isDisableSubstitutableList[i] = 0 ;
                        }
                        request.setAttribute( "isDisableSubstitutableList", isDisableSubstitutableList );
                    }
					// repeting part numbers
					ArrayList repetedPartNumber = new ArrayList();
					repetedPartNumber = NewPackingSlipDAO.getRepetedPartNumbers ( packingSlipForm.getLineitems() );
				
					if( repetedPartNumber.size() > 0 )
					{
						session.setAttribute( "repetedPartNumber", repetedPartNumber );
					}

                    int customerId = NewSalesOrderDAO.getCustomerID( null, packingSlipForm.getSalesOrderId() + "" );
                    ArrayList shippingAddresses =  null;
                    if ( packingSlipForm.getOdmId() > 0 )
                    {
                        shippingAddresses = CustomerDAO.getAllAddressesOfType( packingSlipForm.getOdmId(), Constants.ADDRESS_TYPE_SHIPPING) ;
                        shippingAddresses.add ( 0, CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( packingSlipForm.getOdmId() ) ) );
                        shippingAddresses.add ( CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( customerId ) ) );
                    }
                    else
                    {
                        shippingAddresses = CustomerDAO.getAllAddressesOfType( customerId, Constants.ADDRESS_TYPE_SHIPPING) ;
                        shippingAddresses.add ( 0, CustomerDAO.getAddress ( SalesOrderDAO.getDefaultShippingAddressId( customerId ) ) );
                    }
                    session.setAttribute ( "psShippingAddresses", loadAddresses( shippingAddresses ) );

                    ArrayList billingAddresses = CustomerDAO.getAllAddressesOfType( customerId, Constants.ADDRESS_TYPE_BILLING) ;
                    billingAddresses.add ( 0, CustomerDAO.getAddress ( SalesOrderDAO.getDefaultBillingAddressId( customerId ) ) );
                    request.setAttribute ( "psBillingAddresses", loadAddresses( billingAddresses ) );
                }
				session.setAttribute ( "packingSlipForm", packingSlipForm );
			}
			else
			{
				errors.put ("Internal Server Error", "Could not load Packing Slip");
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
				request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
				returnVal = "packingSlipMenu";
			}
		}
		else
		{
			errors.put ("Internal Server Error", "Could not load Packing Slip");
			errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
			request.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not load Packing Slip" );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
			returnVal = "packingSlipMenu";
		}
		return ( mapping.findForward ( returnVal ) );
	}

  // Added by Neelima on 27-04 -2004
	public ArrayList setPackingSlipOrder ( ArrayList packingSlipListBySalesOrderId , String currentLabel )
	{
		ArrayList   packingSlipListBySalesOrderId1 = new ArrayList();
	    try
		{	 
			Iterator packingSlip = packingSlipListBySalesOrderId.iterator();				

			while ( packingSlip.hasNext() )
		 	{
				LabelValueBean packingSlipId = ( LabelValueBean )packingSlip.next();  
				String label = packingSlipId.getLabel();
				if ( ! label.equalsIgnoreCase( currentLabel ) )
				{
					packingSlipListBySalesOrderId1.add( packingSlipId );				   
				}
			}
		}
		catch ( Exception e )
		{
			System.out.println (e);
		}
		return packingSlipListBySalesOrderId1;
	}

    private ArrayList loadAddresses( ArrayList addresses )
    {
        Address address = null;
        ArrayList addressList = new ArrayList ();
        for ( int i = 0; i < addresses.size (); i++ )
        {
            address = ( Address ) addresses.get ( i );
            String addrStr = "";
            if ( ( address.getAddress1 () != null ) && ( address.getAddress1 ().trim ().length () != 0 ) )
            {
                addressList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress1 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress2 () != null ) && ( address.getAddress2 ().trim ().length () != 0 ) )
            {
                addressList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress2 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress3 () != null ) && ( address.getAddress3 ().trim ().length () != 0 ) )
            {
                addressList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress3 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getAddress4 () != null ) && ( address.getAddress4 ().trim ().length () != 0 ) )
            {
                addressList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getAddress4 (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getCity () != null ) && ( address.getCity ().trim ().length () != 0 ) )
            {
                addressList.add ( new org.apache.struts.util.LabelValueBean (
                        address.getCity (), Integer.toString ( address.getAddressId () ) ) );
            }
            if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
            {
                addrStr = addrStr + address.getState ();
            }
            if ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) )
            {
                if ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) )
                {
                    addrStr = addrStr + "-";
                }
                addrStr = addrStr + address.getZipCode ();
            }
            if ( ( address.getCountry () != null ) && ( address.getCountry ().trim ().length () != 0 ) )
            {
                if ( ( ( address.getZipCode () != null ) && ( address.getZipCode ().trim ().length () != 0 ) ) || ( ( address.getState () != null ) && ( address.getState ().trim ().length () != 0 ) ) )
                {
                    addrStr = addrStr + ",";
                }
                addrStr = addrStr + address.getCountry ();
            }
            if ( !( "".equals ( addrStr ) ) )
            {
                addressList.add ( new org.apache.struts.util.LabelValueBean ( addrStr, Integer.toString ( address.getAddressId () ) ) );
            }
            addressList.add ( new org.apache.struts.util.LabelValueBean ( "", Integer.toString ( address.getAddressId () ) ) );
        }

        return addressList;
    }

    public static String getAddressAsString( Address address )
    {
        StringBuffer tempAddress = new StringBuffer( "" );
        String contactPerson = address.getContactPerson();
        String address1 = address.getAddress1();
        String address2 = address.getAddress2();
        String address3 = address.getAddress3();
        String address4 = address.getAddress4();
        String city = address.getCity();
        String zipCode = address.getZipCode();
        String state = address.getState();
        String country = address.getCountry();
        String phoneNumber = address.getPhoneNumber();
        String cellNumber = address.getCellNumber();
        String faxNumber = address.getFaxNumber();
        String email = address.getEmail();

        if( contactPerson != null && !( contactPerson.trim().equals( "" ) ) )
        {
            tempAddress.append( contactPerson + "\n" );
        }
        if( address1 != null && !( address1.trim().equals( "" ) ) )
        {
            tempAddress.append( address1 + "\n" );
        }
        if( address2 != null && !( address2.equals( "" ) ) )
        {
            tempAddress.append( address2 + "\n" );
        }
        if( address3 != null && !( address3.equals( "" ) ) )
        {
            tempAddress.append( address3 + "\n" );
        }
        if( address4 != null && !( address4.equals( "" ) ) )
        {
            tempAddress.append( address4 + "\n" );
        }
        if( city != null && !( city.equals( "" ) ) )
        {
            tempAddress.append( city + "\n" );
        }
        if( state != null && !( state.equals( "" ) ) )
        {
            tempAddress.append( state );
        }
        if( zipCode != null && !( zipCode.equals( "" ) ) )
        {
            if( state != null && !( state.equals( "" ) ) )
            {
                tempAddress.append( " - " );
            }
            tempAddress.append( zipCode );
        }
        if( country != null && !( country.equals( "" ) ) )
        {
            if( ( zipCode != null && !( zipCode.equals( "" ) ) ) || ( state != null && !( state.equals( "" ) ) ) )
            {
                tempAddress.append( ", " );
            }
            tempAddress.append( country );
        }
        tempAddress.append( ( phoneNumber != null && !( phoneNumber.equals( "" ) ) ) ? "\n\nTel:" + phoneNumber : "" );
        tempAddress.append( ( cellNumber != null && !( cellNumber.equals( "" ) ) ) ? "\nCell:" + cellNumber : "" );
        tempAddress.append( ( faxNumber != null && !( faxNumber.equals( "" ) ) ) ? "\nFax:" + faxNumber : "" );
        tempAddress.append( ( email != null && !( email.equals( "" ) ) ) ? "\nEmail:" + email : "" );
        return tempAddress.toString();
    }
}